import { ref, onMounted, watch, nextTick } from 'vue'
import storage from 'good-storage'
import { USER_KEY } from '@/assets/js/constant'
export default function useMessage(props) {
  const scrollRef = ref(null)
  const msgsRef = ref(null)

  watch(() => props.data, async () => {
    console.log('+')
    await nextTick()
    scrollTo(props.data.length - 1)
  })

  onMounted(() => {
    scrollTo(msgsRef.value.children.length - 1)
  })

  function scrollTo(index) {
    if (isNaN(index) || index < 0) {
      return
    }
    const targetEl = msgsRef.value.children[index]
    const scroll = scrollRef.value.scroll
    scroll.scrollToElement(targetEl)
  }

  function bubbleBelone(uid) {
    const userId = storage.session.get(USER_KEY).userId
    return userId === uid ? 'me' : 'you'
  }

  return {
    scrollRef,
    msgsRef,
    scrollTo,
    bubbleBelone
  }
}
